package com.lius.SpringBootStart.intercepter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lius.SpringBootStart.domain.User;
import com.lius.SpringBootStart.service.UserService;
import com.lius.SpringBootStart.utils.JsonData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

public class LoginIntercepter implements HandlerInterceptor {

    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取传入token
        String token = request.getHeader("token");
        System.out.println(userService.getUser());

        if (!StringUtils.hasLength(token)) {
            token = request.getParameter("token");
        }

        if (!StringUtils.hasLength(token)) {
            renderJson(response, JsonData.buildError("参数异常，未定义token", -10));
            return false;
        } else {
            // 判断token是否合法 :TODO
            User user = userService.getUserByToekn(token);
            if (user == null) {
                renderJson(response, JsonData.buildError("错误的token", -12));
                return false;
            }
        }

        return true;
    }


    private void renderJson(HttpServletResponse response, JsonData jsonData) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");

        try (PrintWriter writer = response.getWriter()) {
            // 因为println只能输出String，需要将JosnData对象转为String
            String json = (new ObjectMapper()).writeValueAsString(jsonData);
            writer.println(json);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
